<div class="layui-fluid layui-anim febs-anim" id="febs-user" lay-title="用户管理">
    <form class="jhg-body layui-form layui-table-form" lay-filter="user-table-form">
        <div class="jhg-body-search">
            <div class="layui-form-item">
                <div th:class="${isAdmin ? 'layui-inline' : 'layui-inline febs-hide'}">
                    <label class="layui-form-label layui-form-label-sm">机构中心</label>
                    <div class="layui-input-inline">
                        <select name="deptId" id = "deptQuery" >
                            <option value=""></option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">用户名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="userName" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">姓名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="uname" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label layui-form-label-sm">手机</label>
                    <div class="layui-input-inline">
                        <input type="text" name="mobile" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline">
                    <div id="query" class="layui-btn layui-btn-sm">
                        <em class="layui-icon">&#xe615;</em> 查询
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div class="jhg-body-button">
        <div id="add" class="layui-btn layui-btn-sm">
            <em class="layui-icon">&#xe654;</em> 新增
        </div>
        <div id="delete" class="layui-btn layui-btn-sm layui-btn-warm">
            <em class="layui-icon">&#xe640;</em> 批量删除
        </div>
        <div id="resetPw" class="layui-btn layui-btn-sm layui-btn-warm" shiro:hasPermission="user:password:reset">
            <em class="layui-icon">&#xe642;</em> 重置密码
        </div>
    </div>

    <div class="jhg-body-table">
        <table lay-filter="userTable" lay-data="{id: 'userTable'}"></table>
    </div>

</div>
<script type="text/html" id="user-status">
    {{#
    var status = {
    1: {title: '有效', color: 'green'},
    0: {title: '禁用', color: 'volcano'}
    }[d.status];
    }}
    <span class="layui-badge febs-tag-{{status.color}}">{{ status.title }}</span>
</script>
<script type="text/html" id="user-sex">
    {{#
    var sex = {
    2: {title: '保密'},
    1: {title: '女'},
    0: {title: '男'}
    }[d.sex];
    }}
    <span>{{ sex.title }}</span>
</script>
<script type="text/html" id="user-option">
    <span shiro:lacksPermission="user:view,user:update,user:delete">
        <span class="layui-badge-dot febs-bg-orange"></span> 无权限
    </span>
    <a lay-event="detail" shiro:hasPermission="user:view"><em
            class="layui-icon febs-edit-area febs-green">&#xe7a5;</em></a>
    <a lay-event="edit" shiro:hasPermission="user:update"><em
            class="layui-icon febs-edit-area febs-blue">&#xe7a4;</em></a>
    <a lay-event="del" shiro:hasPermission="user:delete"><em class="layui-icon febs-edit-area febs-red">&#xe7f9;</em></a>
</script>
<script data-th-inline="none" type="text/javascript">
    layui.use(['dropdown', 'jquery', 'laydate', 'form', 'table', 'febs', 'treeSelect'], function () {
        var $ = layui.jquery,
            laydate = layui.laydate,
            febs = layui.febs,
            form = layui.form,
            table = layui.table,
            treeSelect = layui.treeSelect,
            dropdown = layui.dropdown,
            $view = $('#febs-user'),
            $query = $view.find('#query'),
            $add = $view.find('#add'),
            $delete = $view.find('#delete'),
            $resetPw = $view.find('#resetPw'),
            $reset = $view.find('#reset'),
            $searchForm = $view.find('form'),
            sortObject = {field: 'createTime', type: null},
            tableIns;

        form.render();

        initTable();

        laydate.render({
            elem: '#createTime',
            range: true,
            trigger: 'click'
        });

        dropdown.render({
            elem: $view.find('.action-more'),
            click: function (name, elem, event) {
                var checkStatus = table.checkStatus('userTable');
                if (name === 'add') {

                }
                if (name === 'delete') {

                }
                if (name === 'reset') {

                }
                if (name === 'export') {
                    var params = $.extend(getQueryParams(), {field: sortObject.field, order: sortObject.type});
                    params.pageSize = $view.find(".layui-laypage-limits option:selected").val();
                    params.pageNum = $view.find(".layui-laypage-em").next().html();
                    febs.download(ctx + 'user/excel', params, '用户信息表.xlsx');
                }
            },
            options: [{
                name: 'add',
                title: '新增用户',
                perms: 'user:add'
            }, {
                name: 'delete',
                title: '删除用户',
                perms: 'user:delete'
            }, {
                name: 'reset',
                title: '密码重置',
                perms: 'user:password:reset'
            }]
        });

        getDeptList();

        //获取部门
        function getDeptList() {
            febs.get(ctx + 'user/dept/list', null, function (data) {
                var newdata = data.data
                //debugger
                //$view.find("#dockId").append('<option value="">全部</option>')
                for (var i = 0; i < newdata.length; i++) {
                    $view.find("#deptQuery").append("<option value='" + newdata[i].deptId.toString() + "'>" + newdata[i].deptName + "</option>")
                }
                form.render('select'); //刷新select选择框渲染
            })

        }

        table.on('tool(userTable)', function (obj) {
            var data = obj.data,
                layEvent = obj.event;
            if (layEvent === 'detail') {
                febs.modal.view('用户信息', 'system/user/detail/' + data.userName, {
                    area: $(window).width() <= 750 ? '95%' : '660px'
                });
            }
            if (layEvent === 'del') {
                febs.modal.confirm('删除用户', '确定删除该用户？', function () {
                    deleteUsers(data.userId);
                });
            }
            if (layEvent === 'edit') {
                febs.modal.open('修改用户', 'system/user/update/' + data.userName, {
                    area: $(window).width() <= 750 ? '90%' : '50%',
                    btn: ['提交', '取消'],
                    yes: function (index, layero) {
                        $('#user-update').find('#submit').trigger('click');
                    },
                    btn2: function () {
                        layer.closeAll();
                    }
                });
            }
        });

        table.on('sort(userTable)', function (obj) {
            sortObject = obj;
            tableIns.reload({
                initSort: obj,
                where: $.extend(getQueryParams(), {
                    field: obj.field,
                    order: obj.type
                })
            });
        });

        $query.on('click', function () {
            var params = $.extend(getQueryParams(), {field: sortObject.field, order: sortObject.type});
            tableIns.reload({where: params, page: {curr: 1}});
        });

        $reset.on('click', function () {
            $searchForm[0].reset();
            //treeSelect.revokeNode('dept');
            sortObject.type = 'null';
            tableIns.reload({where: getQueryParams(), page: {curr: 1}, initSort: sortObject});
        });

        $add.on('click', function () {
            febs.modal.open('新增用户', 'system/user/add', {
                btn: ['提交'],
                area: $(window).width() <= 750 ? '95%' : '50%',
                yes: function (index, layero) {
                    $('#user-add').find('#submit').trigger('click');
                },
                btn2: function () {
                    $('#user-add').find('#reset').trigger('click');
                    return false;
                }
            });
        });

        $delete.on('click', function () {
            var checkStatus = table.checkStatus('userTable');
            if (!checkStatus.data.length) {
                febs.alert.warn('请选择需要删除的用户');
            } else {
                febs.modal.confirm('删除用户', '确定删除该用户？', function () {
                    var userIds = [];
                    layui.each(checkStatus.data, function (key, item) {
                        userIds.push(item.userId)
                    });
                    deleteUsers(userIds.join(','));
                });
            }
        });

        $resetPw.on('click', function () {
            var checkStatus = table.checkStatus('userTable');
            if (!checkStatus.data.length) {
                febs.alert.warn('请选择需要重置密码的用户');
            } else {
                var usernames = [];
                layui.each(checkStatus.data, function (key, item) {
                    usernames.push(item.userName)
                });
                febs.post(ctx + 'user/password/reset/' + usernames.join(','), null, function () {
                    febs.alert.success('所选用户密码已重置为系统默认密码');
                });
            }
        });

        function initTable() {
            tableIns = febs.table.init({
                elem: $view.find('table'),
                id: 'userTable',
                height: getTableHeight(),
                url: ctx + 'user/list',
                skin: '',
                cols: [[
                    {type: 'checkbox'},
                    {field: 'userName', title: '用户名', minWidth: 100},
                    {field: 'uname', title: '姓名', minWidth: 80},
                    {field: 'deptName', title: '服务中心'},
                    {field: 'mobile', title: '手机', minWidth: 165},
                    {field: 'email', title: '邮箱', minWidth: 180},
                    //{title: '状态', templet: '#user-status'},
                    //{field: 'createTime', title: '创建时间', minWidth: 180, sort: true},
                    {title: '操作', toolbar: '#user-option', minWidth: 140}
                ]]
            });
        }

        function getTableHeight() {
            var tempHeight = $(document).height() - $(".jhg-body-search").outerHeight(true) - $(".jhg-body-button").outerHeight(true) - 106;
            return tempHeight;
        }

        function getQueryParams() {
            var createTimeFrom,
                createTimeTo,
                createTime = $searchForm.find('input[name="createTime"]').val();
            if (createTime) {
                createTimeFrom = createTime.split(' - ')[0];
                createTimeTo = createTime.split(' - ')[1];
            }
            return {
                createTimeFrom: createTimeFrom,
                createTimeTo: createTimeTo,
                userName: $searchForm.find('input[name="userName"]').val()?.trim(),
                uname: $searchForm.find('input[name="uname"]').val()?.trim(),
                status: $searchForm.find("select[name='status']").val(),
                sex: $searchForm.find("select[name='sex']").val(),
                mobile: $searchForm.find("input[name='mobile']").val()?.trim(),
                deptId: $searchForm.find("input[name='deptId']").val(),
                invalidate_ie_cache: new Date()
            };
        }

        function deleteUsers(userIds) {
            var currentUserId = currentUser.userId + '';
            if (('' + userIds).split(',').indexOf(currentUserId) !== -1) {
                febs.alert.warn('所选用户包含当前登录用户，无法删除');
                return;
            }
            febs.get(ctx + 'user/delete/' + userIds, null, function () {
                febs.alert.success('删除用户成功');
                $query.click();
            });
        }
    })
</script>